package com.jiuyin.dianjing.ui.activity.team;

import android.app.AlertDialog;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.HeadPhotoAdapter;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.constant.ApiConstant;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.Team;
import com.jiuyin.dianjing.model.TeamDetail;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.activity.setting.SettingActivity;
import com.jiuyin.dianjing.ui.fragment.team.TeamGameRecordsFragment;
import com.jiuyin.dianjing.ui.fragment.team.TeamsFragment;
import com.jiuyin.dianjing.util.DataCleanManagerUtil;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.jiuyin.dianjing.view.ExpandTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_MODEL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TEAMID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_ATTENTION_TEAM;

public class TeamDetailNewActivity extends BaseActivity {
    @BindView(R.id.bt_quit)
    Button btQuit;
    @BindView(R.id.tv_watch)
    CheckedTextView tvWatch;
    @BindView(R.id.tv_join)
    TextView tvJoin;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_school)
    TextView tvSchool;
    @BindView(R.id.tv_watch_num)
    TextView tvWatchNum;
    @BindView(R.id.tv_intro)
    ExpandTextView tvIntro;
    @BindView(R.id.grid_members)
    RecyclerView gridMembers;
    @BindView(R.id.grid_often_games)
    RecyclerView gridGames;

    Team mTeam;
    private TeamDetail mTeamDetail;
    private HeadPhotoAdapter membersAdapter;
    private HeadPhotoAdapter gamesAdapter;
    private String TYPE_DISSOLVE = "1";
    private String TYPE_QUIT = "2";

    @Override
    protected int setLayoutId() {
        return R.layout.activity_team_detail_new;
    }

    @Override
    protected void initData() {
        mTeam = (Team) getIntent().getSerializableExtra("team");
        setTitle(mTeam.name);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.layout_fragment, TeamGameRecordsFragment.newInstance(mTeam.team_id))
                .commit();
        fetchDetailData();
    }

    void fetchDetailData() {
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TEAMID, mTeam.team_id);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback requestCallback = new DefaultApiResult() {

            @Override
            public void onSuccess(JsonObject data) {
                mTeamDetail = new Gson().fromJson(data, TeamDetail.class);
                initView();
            }
        };
        ServerApi.post(ApiEnum.TEAM_DETAIL, data, null, progress, d -> addDisposable(d), requestCallback);
    }

    @Override
    protected void initView() {
        if (mTeamDetail != null) {
            Glide.with(this)
                    .load(mTeamDetail.team.logo)
                    .override(DisplayUtil.dp2px(this, 50))
                    .into(ivHead);
            tvName.setText(mTeamDetail.team.name);

            tvIntro.setContent(mTeamDetail.team.intro);
            tvSchool.setText(mTeamDetail.universityClubName != null ? mTeamDetail.universityClubName : "");
            tvWatchNum.setText(mTeamDetail.fans_num + "关注");
            if (mTeamDetail.isJoin == 1) {
                tvJoin.setVisibility(View.GONE);
            } else if (mTeamDetail.isJoin == 0) {
                tvJoin.setVisibility(View.VISIBLE);
            } else {//2 申请中
                tvJoin.setVisibility(View.VISIBLE);
                tvJoin.setText("申请中");
                tvJoin.setEnabled(false);
            }
            if (mTeamDetail.isAttention == 1) {
                tvWatch.setText("已关注");
                tvWatch.setChecked(true);
            } else {
                tvWatch.setText("关注");
                tvWatch.setChecked(false);
            }
            membersAdapter.setData(mTeamDetail.headerList);
            gamesAdapter.setData(mTeamDetail.gameList);
            //职位(0 队长 1 管理 2 成员 3未加入)
            switch (mTeamDetail.part) {
                case 0:
                    btQuit.setVisibility(View.VISIBLE);
                    btQuit.setText("解散战队");
                    btQuit.setOnClickListener(v -> {
                        showDialog(R.string.dialog_content_dissolution_team, TYPE_DISSOLVE);
                    });
                    break;
                case 1:
                case 2:
                    btQuit.setVisibility(View.VISIBLE);
                    btQuit.setOnClickListener(v -> {
                        showDialog(R.string.dialog_content_quit_team, TYPE_QUIT);

                    });
                    break;
                default:
                    btQuit.setVisibility(View.GONE);
                    break;
            }
        } else {
            Glide.with(this)
                    .load(mTeam.logo)
                    .override(DisplayUtil.dp2px(this, 50))
                    .into(ivHead);
            tvName.setText(mTeam.name);
            if (mTeam.intro != null) {
                tvIntro.setContent(mTeam.intro);
            }
            membersAdapter = new HeadPhotoAdapter(40f);
            gamesAdapter = new HeadPhotoAdapter(40f);
            gridMembers.setAdapter(membersAdapter);
            gridGames.setAdapter(gamesAdapter);
            gridMembers.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
            gridGames.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        }
    }

    private void showDialog(int message, String type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TeamDetailNewActivity.this);
        builder.setTitle(R.string.dialog_title_tips)
                .setMessage(message)
                .setPositiveButton(getString(R.string.dialog_confirm_tips),
                        (dialog, whichButton) -> {
                            if (type.equals(TYPE_DISSOLVE)) {
                                dissolveTeam();
                            } else if (type.equals(TYPE_QUIT)) {
                                quitTeam();
                            }
                        }
                )
                .setNegativeButton(getString(R.string.dialog_cancel_tips), null
                )
                .setCancelable(false);
        builder.show();
    }

    private void dissolveTeam() {
        btQuit.setEnabled(false);
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TEAMID, mTeam.team_id);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback apiRequestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                btQuit.setEnabled(true);
                ToastUtil.showShort("解散成功");
                finish();
                EventBus.getDefault().post(new RefreshEvent(TeamsFragment.class.getSimpleName()));
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                btQuit.setEnabled(true);
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                btQuit.setEnabled(true);
            }
        };
        ServerApi.post(ApiEnum.DISSOLVE_TEAM, data, null, progress, d -> addDisposable(d), apiRequestCallback);
    }

    private void quitTeam() {
        btQuit.setEnabled(false);
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TEAMID, mTeam.team_id);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                btQuit.setEnabled(true);
                ToastUtil.showShort("退出成功");
                finish();
                EventBus.getDefault().post(new RefreshEvent(TeamsFragment.class.getSimpleName()));
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                btQuit.setEnabled(true);
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                btQuit.setEnabled(true);
            }
        };
        ServerApi.post(ApiEnum.USER_QUIT_TEAM, data, null, progress, d -> addDisposable(d), requestCallback);
    }

    @OnClick({R.id.bt_quit, R.id.tv_join, R.id.tv_watch, R.id.tv_all_members})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_join:
                Intent intent = new Intent(this, JoinTeam2Activity.class);
                intent.putExtra(KEY_TEAMID, mTeam.team_id);
                startActivity(intent);
                break;
            case R.id.tv_watch:
                watch();
                break;
            case R.id.tv_all_members:
                intent = new Intent(this, TeamMembersActivity.class);
                intent.putExtra(KEY_TEAMID, mTeam.team_id);
                if (null != mTeamDetail) {
                    intent.putExtra(ApiConstant.KEY_PART, mTeamDetail.part);
                }
                startActivity(intent);
                break;
        }
    }

    private void watch() {
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        hashMap.put("targetId", mTeam.team_id);
        hashMap.put("type", tvWatch.isChecked() ? 0 : 1);
        hashMap.put(KEY_ATTENTION_MODEL, VALUE_ATTENTION_TEAM);
        JSONObject json = new JSONObject(hashMap);
        ApiResultCallback apiResultCallback = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                tvWatch.setEnabled(true);
                boolean isAttention = data.get("isAttention").getAsInt() == 1;
                tvWatch.setChecked(isAttention);
                if (tvWatch.isChecked()) {
                    tvWatch.setText("已关注");
                } else {
                    tvWatch.setText("关注");
                }
            }

            @Override
            public void onFail(String msg) {
                tvWatch.setEnabled(true);
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                tvWatch.setEnabled(true);
                LogUtil.log(msg);
            }
        };
        tvWatch.setEnabled(false);
        ServerApi.post(ApiEnum.APP_ADD_ATTENTION_LOG.getUrl(), json, null,
                progress, d -> addDisposable(d), apiResultCallback);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            fetchDetailData();
        }
    }
}
